package com.erbao.classloader;

import java.io.*;

/**
 * @author CaoBaoYin
 * @since 22/3/24 17:21
 */
public class CustomClassLoader extends ClassLoader {

    @Override
    protected Class<?> findClass(String name) throws ClassNotFoundException {
        File file = new File("C:\\JavaWorkspace\\IntelliJIdea\\study\\SpringBoot\\biz-base\\target\\classes".concat(File.separator).concat(name.replaceAll("\\.", "\\\\")).concat(".class"));
        if (! file.exists()) {
            System.out.println(file.getAbsolutePath());
            throw new ClassNotFoundException(name.concat(" is not found"));
        }

        byte[] bytes = null;
        try (FileInputStream fi = new FileInputStream(file);
             ByteArrayOutputStream baos = new ByteArrayOutputStream();) {
            byte[] buffer = new byte[1024];
            int size = 0;
            while ((size = fi.read(buffer)) != -1) {
                baos.write(buffer, 0, size);
            }

            bytes = baos.toByteArray();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return defineClass(name, bytes, 0, bytes.length);
    }

    public static void main(String[] args) {
        try {
            Class<?> clazz = new CustomClassLoader().loadClass("com.erbao.biz.entity.vo.DictVo", false);
            System.out.println(clazz.getName());
            System.out.println(clazz.getClassLoader());
            System.out.println(clazz.getClassLoader().getParent());
            System.out.println(clazz.getClassLoader().getClass().getClassLoader());
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }



    }
}
